package com.liao.badminton.exception;


import com.liao.badminton.code.RespCodeMessage;
import com.liao.badminton.code.ResponseRest;
import com.liao.badminton.code.util.ResponseUtils;
import lombok.extern.log4j.Log4j2;
import org.springframework.security.authentication.*;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * author liaocheng
 * description : 认证异常
 * DATE: 2021/2/22
 */
@Component
@Log4j2
public class MyAuthenticationException implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException, ServletException {
        ResponseRest result;
        log.error("认证异常 {}", e);
        String requestURI = request.getRequestURI();
        if (e instanceof UsernameNotFoundException || e instanceof BadCredentialsException) {
            result = ResponseRest.fail(requestURI, RespCodeMessage.SECURITY_LOGIN_ERROR, e.getMessage());
        } else if (e instanceof LockedException) {
            result = ResponseRest.fail(requestURI, RespCodeMessage.SECURITY_ACCOUNT_LOCK);
        } else if (e instanceof CredentialsExpiredException) {
            result = ResponseRest.fail(requestURI, RespCodeMessage.SECURITY_CREDENTIAL_EXPIRE);
        } else if (e instanceof AccountExpiredException) {
            result = ResponseRest.fail(requestURI, RespCodeMessage.SECURITY_ACCOUNT_EXPIRE);
        } else if (e instanceof DisabledException) {
            result = ResponseRest.fail(requestURI, RespCodeMessage.SECURITY_ACCOUNT_FORBIDDEN);
        } else if (e instanceof InsufficientAuthenticationException) {
            result = ResponseRest.fail(requestURI, RespCodeMessage.SECURITY_ACCOUNT_UN_LOGIN, e.getMessage());
//            response.addHeader("WWW-Authenticate", "Basic realm=\"" + "Realm" + "\"");
//            response.sendError(HttpStatus.UNAUTHORIZED.value(), HttpStatus.UNAUTHORIZED.getReasonPhrase());
//            RequestDispatcher requestDispatcher = request.getRequestDispatcher("/security/index.html");
//            requestDispatcher.forward(request,response);
//            response.setStatus(HttpStatus.HTTP_MOVED_PERM);
//            response.sendRedirect("/security/index.html");
        } else {
            result = ResponseRest.fail(requestURI).setMsg(e.getMessage());
        }
//        response.sendError(result.getCode(), result.getMsg());
        ResponseUtils.out(response, result);
    }

}
